using System;
using System.Collections.Generic;

namespace KharaPos.Web.Models.Shared
{
    public class Equality<T> : IEqualityComparer<T>
    {
        private readonly Func<T, int> _hashFunc;
        private readonly Func<T, T, bool> _equalsFunc;

        public Equality(Func<T,int>hashFunc)
        {
            _hashFunc = hashFunc;
            _equalsFunc = (x, y) => x.GetHashCode() == y.GetHashCode();
        }

        public Equality(Func<T,int>hashFunc, Func<T,T,bool>equalsFunc )
        {
            _hashFunc = hashFunc;
            _equalsFunc = equalsFunc;
        }

        public bool Equals(T x, T y)
        {
            //can't compare null
            if (typeof(T).IsClass)
            {
                if (x == null || y == null)
                    return false;
            }
            return _equalsFunc(x, y);
        }

        public int GetHashCode(T obj)
        {
            return _hashFunc(obj);
        }
    }
}